import React from 'react';
import {
  Form, Input, Button, Select, InputNumber, message, Icon,
} from 'antd';
import { createDeployment } from 'services/deployment';

const { Option } = Select;
let indexLength = 0;
const serviceNamePattern = /^[a-z]([-a-z0-9]*[a-z0-9])?$/;

class Creation extends React.Component {
  handleSubmit = async (e) => {
    e.preventDefault();
    const {
      form: { getFieldsValue, validateFieldsAndScroll },
      updateData,
      closeModal,
    } = this.props;

    try {
      await validateFieldsAndScroll();
      const {
        keys, values, port, image, name,
      } = getFieldsValue();
      const ports = [port];
      const env = keys
        ? keys.reduce((prev, cur, index) => ({ ...prev, [cur]: values[index] }), {})
        : null;
      const data = {
        image,
        name,
        ports,
        env,
      };
      await createDeployment(data);
      message.success('创建成功!');
      await updateData();
      closeModal();
    } catch (err) {
      console.error(err);
    }
  }

  removeEnvVar = (i) => {
    const { form } = this.props;
    const keys = form.getFieldValue('index');
    form.setFieldsValue({
      index: keys.filter((key) => key !== i),
    });
  }

  addEnvVar = () => {
    const { form } = this.props;
    const index = form.getFieldValue('index');
    const nextIndex = index.concat(indexLength);
    indexLength += 1;
    form.setFieldsValue({
      index: nextIndex,
    });
  }

  validateServiceName = (rule, value, callback) => {
    if (value && !serviceNamePattern.test(value)) {
      callback('服务名称不合规! (应只包含小写字母数字与连接符"-", 且以字母开头, 以字母或数字结束)');
    }
    callback();
  }

  render() {
    const { imageList, form: { getFieldDecorator, getFieldValue } } = this.props;
    // index
    getFieldDecorator('index', { initialValue: [] });
    const index = getFieldValue('index');
    const formItems = index.map((i, ind) => (
      <Form.Item label={`环境变量${ind}`} key={`env${i}`}>
        <Form.Item
          label={index === 0 ? '环境变量名称' : ''}
          required={false}
          style={{ display: 'inline-block', width: 'calc(50% - 12px)' }}
        >
          {getFieldDecorator(`keys[${i}]`, {
            validateTrigger: ['onChange', 'onBlur'],
            rules: [
              {
                required: true,
                whitespace: true,
                message: '请输入环境变量名称!',
              },
            ],
          })(<Input placeholder="环境变量名称" style={{ width: '60%', marginRight: 8 }} />)}
        </Form.Item>
        <Form.Item
          label={index === 0 ? '环境变量值' : ''}
          required={false}
          style={{ display: 'inline-block', width: 'calc(50% - 12px)' }}
        >
          {getFieldDecorator(`values[${i}]`, {
            validateTrigger: ['onChange', 'onBlur'],
            rules: [
              {
                required: true,
                whitespace: true,
                message: '请输入环境变量值!',
              },
            ],
          })(<Input placeholder="环境变量值" style={{ width: '60%', marginRight: 8 }} />)}
          <Icon
            className="dynamic-delete-button"
            type="minus-circle-o"
            onClick={() => this.removeEnvVar(i)}
          />
        </Form.Item>
      </Form.Item>
    ));
    return (
      <Form
        labelCol={{ xs: { span: 24 }, sm: { span: 6 } }}
        wrapperCol={{
          xs: { span: 24 },
          sm: { span: 18 },
        }}
        onSubmit={this.handleSubmit}
      >
        <Form.Item label="服务名称">
          {getFieldDecorator('name', {
            rules: [
              {
                required: true,
                message: '请输入服务名称!',

              },
              {
                validator: this.validateServiceName,
              },
            ],
          })(<Input />)}
        </Form.Item>
        <Form.Item label="服务开放端口">
          {getFieldDecorator('port', {
            rules: [
              {
                required: true,
                message: '请输入服务开放端口!',
              },
            ],
            initialValue: 8080,
          })(<InputNumber min={0} max={65535} />)}
        </Form.Item>
        <Form.Item label="镜像">
          {getFieldDecorator('image', {
            rules: [{ required: true, message: '请选择镜像!' }],
          })(
            <Select>
              {
              imageList.map((item) => <Option key={item}>{item}</Option>)
            }
            </Select>,
          )}
        </Form.Item>
        {formItems}
        <Form.Item wrapperCol={{
          xs: { span: 24, offset: 0 },
          sm: { span: 18, offset: 6 },
        }}
        >
          <Button type="dashed" onClick={this.addEnvVar} style={{ width: '60%' }}>
            <Icon type="plus" />
              添加环境变量
          </Button>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
                        提交
          </Button>
        </Form.Item>
      </Form>
    );
  }
}

export default Form.create({})(Creation);
